#!/bin/bash
set -e

# 定义变量
REMOTE_USER="jkdeploy"
REMOTE_HOST="hcss-ecs-d212"
REMOTE_PATH="/app/code/stack"
NGINX_SERVICE="nginx"

# 测试连接
echo "=== 测试 SSH 连接 ==="
if ! ssh ${REMOTE_HOST} "echo 'Connection test successful'"; then
    echo "SSH 连接失败"
    exit 1
fi

# 打包必要文件
echo "=== 创建部署包 ==="
tar czf stack.tar.gz \
    index.html \
    main.js \
    style.css \
    README.md

# 部署到远程服务器
echo "=== 部署到远程服务器 ==="
# 确保目标目录存在
ssh ${REMOTE_HOST} "mkdir -p ${REMOTE_PATH}"

# 传输文件
scp stack.tar.gz ${REMOTE_HOST}:${REMOTE_PATH}/

# 在远程服务器上解压和设置权限
echo "=== 配置远程服务器 ==="
ssh ${REMOTE_HOST} \
    "cd ${REMOTE_PATH} && \
     tar xzf stack.tar.gz && \
     rm stack.tar.gz && \
     sudo systemctl reload ${NGINX_SERVICE}"

# 验证部署
echo "=== 验证部署 ==="
response=$(curl -s -o /dev/null -w "%{http_code}" http://${REMOTE_HOST}:87)
if [ $response -eq 200 ]; then
    echo "部署成功: HTTP $response"
else
    echo "部署可能存在问题: HTTP $response"
    exit 1
fi

# 检查 Nginx 状态
echo "=== Nginx 状态 ==="
ssh ${REMOTE_HOST} \
    "systemctl status ${NGINX_SERVICE} | grep Active"

# 检查日志
echo "=== 最近的访问日志 ==="
ssh ${REMOTE_HOST} \
    "tail -n 5 /var/log/nginx/stack.access.log"

echo "=== 最近的错误日志 ==="
ssh ${REMOTE_HOST} \
    "tail -n 5 /var/log/nginx/stack.error.log"